package com.spring.sunflower.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.spring.sunflower.MainActivity;
import com.spring.sunflower.R;
import com.spring.sunflower.common.LogOutActivity;
import com.spring.sunflower.common.WalletActivity;
import com.spring.sunflower.common.WebViewActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.dialog.NoticeDialog;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.http.AppRetrofit;
import com.spring.sunflower.util.ActivityManager;
import com.spring.sunflower.util.LocationUtils;
import com.spring.sunflower.util.NetUtils;
import com.spring.sunflower.widget.GlideEngine;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMMessageReceipt;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by Kevin on 2021/5/19<br/>
 * <p>
 * Describe:<br/>
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppBaseActivity implements BaseView {
    public T mPresenter;
    public ActionBar actionBar;
    public TextView tvTitle, tvFunctionX;
    private LoadingPopupView mLoadingView;
    public boolean mGrantedCameraPermission;
    public boolean mGrantedStoragePermission;
    public boolean mGratedRecordPermission;

    @Override
    public void onStart() {
        super.onStart();
        if (shouldRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (shouldRegisterEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    public boolean shouldRegisterEventBus() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        doSomethingBeforeOnCreate();
        super.onCreate(savedInstanceState);
        setContentView(getLayoutID());
        mGrantedCameraPermission = XXPermissions.isGranted(this, Permission.CAMERA);
        mGrantedStoragePermission = XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
        mGratedRecordPermission = XXPermissions.isGranted(this, Permission.RECORD_AUDIO);
        Toolbar toolBar = findViewById(R.id.toolBar);
        tvTitle = findViewById(R.id.tvTitle);
        tvFunctionX = findViewById(R.id.tvFunctionX);
        if (toolBar != null) {
            setSupportActionBar(toolBar);
        }
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            printD("supportActionBar != null");
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle("");
        } else {
            printD("supportActionBar == null");
        }
        mPresenter = setPresenter();
        initView();
        mApp = (BaseApplication) getApplicationContext();
    }

    public abstract int getLayoutID();

    public abstract T setPresenter();

    public abstract void initView();

    @Override
    protected void onResume() {
        super.onResume();
        ActivityManager.getActivityManager().pushActivity(this);
        if (mApp != null) {
            mApp.setCurrentActivity(this);
        }
        if (!NetUtils.isNetworkAvailable(this)) {
            showToast("网络无连接");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager.getActivityManager().popActivity(this);
        clearCurrentActivity();
    }


    public void startNewActivity(Class<? extends BaseActivity> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        printD("onOptionsItemSelected==" + (item.getItemId() == android.R.id.home));
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return true;
    }

    public void doSomethingBeforeOnCreate() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
//        for (int i = 0; i < runningAppProcesses.size(); i++) {
//            String processName = runningAppProcesses.get(i).processName;
//            LogUtils.INSTANCE.logD("BaseActivity", "processName=" + processName);
//
//        }
//        if (!runningAppProcesses.isEmpty()) {
//            ActivityManager.RunningAppProcessInfo runningAppProcessInfo = runningAppProcesses.get(0);
//            if (!Constant.PACKAGE_NAME.equals(runningAppProcessInfo.processName)) {
//                LogUtils.INSTANCE.logD("BaseActivity", "app was killed");
//                extracted();
//            }
//        } else {
//            LogUtils.INSTANCE.logD("BaseActivity", "app was killed~~");
//            extracted();
//        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    private void extracted() {
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
            }

            @Override
            public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {
                super.onRecvC2CReadReceipt(receiptList);
            }

            @Override
            public void onRecvMessageRevoked(String msgID) {
                super.onRecvMessageRevoked(msgID);
            }

            @Override
            public void onRecvMessageModified(V2TIMMessage msg) {
                super.onRecvMessageModified(msg);
            }
        });
    }

    @Override
    public void showLoading() {
        if (mLoadingView == null) {
            mLoadingView = new XPopup.Builder(this)
                    .isRequestFocus(false)
                    .autoFocusEditText(false)
                    .asLoading();
        }
        if (!mLoadingView.isShown()) {
            mLoadingView.show();
        }

    }

    @Override
    public void hideLoading() {
        if (mLoadingView != null && mLoadingView.isShown()) {
            mLoadingView.dismiss();
            mLoadingView = null;
        }
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void showError(int errorCode, String msg) {
//        showToast("ErrorCode=" + errorCode + "::msg=" + msg);
        showToast(msg);
    }

    @Override
    public void onErrorCode(BaseModel model) {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onProgress(int progress) {

    }

    @Override
    public void requestFinish() {

    }

    @Override
    public void requestFinishWithSth(String type) {

    }

    @Override
    public void showTokenExpired() {
        MobclickAgent.onProfileSignOff();
        showToast("登录已失效，请重新登录");
        LocationUtils.getInstance(this).stop();
        AppRetrofit.destroy();
        BaseFragment.mStrangeListData.clear();
        clearStorageUserData();
        goLoginActivity();
    }

    @Override
    public void showNeedCharge() {
        NoticeDialog dialog = new NoticeDialog(this, new OnPermissionIntroClickListener() {
            @Override
            public void onClickCancel() {
            }

            @Override
            public void onClickOK() {
                Intent intent = new Intent(BaseActivity.this, WalletActivity.class);
                startActivity(intent);
            }
        });
        dialog.setOnCreateViewListener(new NoticeDialog.OnCreateViewListener() {
            @Override
            public void onCreateView() {
                TextView tv = dialog.findViewById(R.id.tv);
                TextView tvTitle = dialog.findViewById(R.id.tvTitle);
                TextView tvDesc = dialog.findViewById(R.id.tvDesc);
                tvTitle.setText("余额提醒");
                tvDesc.setText("当前余额不足，无法进行该操作");
                tvDesc.setTextColor(getColorX(R.color.red_2));
                TextView tvOK = dialog.findViewById(R.id.tvOK);
                tvOK.setText("去充值");
            }
        });
        new XPopup.Builder(this)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .dismissOnTouchOutside(false)
                .asCustom(dialog)
                .show();
    }

    public void backLogin() {
        MobclickAgent.onProfileSignOff();
        LocationUtils.getInstance(this).stop();
        AppRetrofit.destroy();
        BaseFragment.mStrangeListData.clear();
        clearStorageUserData();
        goLoginActivity();
    }

    private void goLoginActivity() {
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
            }

            @Override
            public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {
                super.onRecvC2CReadReceipt(receiptList);
            }

            @Override
            public void onRecvMessageRevoked(String msgID) {
                super.onRecvMessageRevoked(msgID);
            }

            @Override
            public void onRecvMessageModified(V2TIMMessage msg) {
                super.onRecvMessageModified(msg);
            }
        });
        V2TIMManager.getInstance().logout(new V2TIMCallback() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
                V2TIMManager.getInstance().unInitSDK();
            }
        });
        Intent intent = new Intent(this, LogOutActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        forbiddenBackKey = true;
//        showHelpDialog("温馨提示", "当前登录已失效，需要退出app重新进入才可以使用", new OnPermissionIntroClickListener() {
//            @Override
//            public void onClickCancel() {
//
//            }
//
//            @Override
//            public void onClickOK() {
                ActivityManager.getActivityManager().clearAllActivity();
//                forbiddenBackKey = false;
//                Intent intent = new Intent(this, LogOutActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//            }
//        });
    }

//    public void clearStorageUserData() {
//        saveField(Constant.KEY_TOKEN, "");
//        saveField(Constant.KEY_GENDER, "");
//        saveField("birthday", "");
//        saveField(Constant.KEY_SIGNATURE, "");
//        saveField(Constant.KEY_NICKNAME, "");
//        saveField(Constant.KEY_TYPE, "");
//        saveField(Constant.KEY_USERID, "");
//        saveField(Constant.KEY_PHOTO, "");
//        saveField(Constant.KEY_MOBILE, "");
//        saveField(Constant.KEY_WEALTH, "");
//        saveField(Constant.KEY_USERID_CHATTER, "");
//        saveField(Constant.KEY_AVATAR_CHATTER, "");
//        saveField(Constant.KEY_NICKNAME_CHATTER, "");
//        saveField(Constant.KEY_CHATTER_PRICE, "");
//        saveField(Constant.CHATTED_TIME_STORAGE,"");
//    }

    public void goHome(int index) {
        Intent intent = new Intent(this, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("switch2Index", index);
        startActivity(intent);
    }

    public void goAgreement() {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra(Constant.KEY_WEB_VIEW_TITLE, "用户协议");
        intent.putExtra(Constant.KEY_WEB_VIEW_URL, Constant.REGISTER_AGREEMENT);
        startActivity(intent);
    }

    public void goPrivateAgreement() {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra(Constant.KEY_WEB_VIEW_TITLE, "隐私协议");
        intent.putExtra(Constant.KEY_WEB_VIEW_URL, Constant.PRIVATE_AGREEMENT);
        startActivity(intent);
    }

    //    public void showPermissionIntroDialog(BasePopupView popupView) {
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .asCustom(popupView)
//                .show();
//    }
//
//    public void showPermissionIntroDialog(String title, String desc, OnPermissionIntroClickListener listener) {
//        PermissionIntroDialog dialog = new PermissionIntroDialog(this, R.layout.dialog_permission_intro, listener);
//        TextView tvTitle = dialog.findViewById(R.id.tvTitle);
//        TextView tvDesc = dialog.findViewById(R.id.tvDesc);
//        tvTitle.setText(title);
//        tvDesc.setText(desc);
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .asCustom(dialog)
//                .show();
//    }
//
//    public void showPermissionIntroDialog(String[] titleArr, String[] descArr, OnPermissionIntroClickListener listener) {
//        PermissionIntroDialog dialog = new PermissionIntroDialog(this, R.layout.dialog_permission_intro_list, listener);
//        LinearLayout llContainer = dialog.findViewById(R.id.llContainer);
//        for (int i = 0; i < titleArr.length; i++) {
//            View inflate = View.inflate(this, R.layout.dialog_permission_intro_list, null);
//            TextView tvTitle = inflate.findViewById(R.id.tvTitle);
//            TextView tvDesc = inflate.findViewById(R.id.tvDesc);
//            tvTitle.setText(titleArr[i]);
//            tvDesc.setText(descArr[i]);
//            llContainer.addView(inflate);
//        }
//
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .asCustom(dialog)
//                .show();
//    }
    public void checkOpenGallery(Context context, boolean enableCrop) {
        if (XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(getString(R.string.permission_camera_title), getString(R.string.permission_camera_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGallery(false, enableCrop);
                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    mGrantedCameraPermission = true;
                                    openGallery(true, enableCrop);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    openGallery(false, enableCrop);
                                }
                            });

                }
            });
        } else if (XXPermissions.isGranted(this, Permission.CAMERA) && !XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)) {
            showPermissionIntroDialog(getString(R.string.permission_storate_title), getString(R.string.permission_storate_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGallery(true, enableCrop);

                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    mGrantedStoragePermission = true;
                                    openGallery(true, enableCrop);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                }
                            });
                }
            });
        } else if (!XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(new String[]{getString(R.string.permission_storate_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_storate_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        mGrantedStoragePermission = true;
                                        mGrantedCameraPermission = true;
                                        openGallery(true, enableCrop);
                                    } else {
                                        if (permissions.contains(Permission.CAMERA)) {
                                            mGrantedCameraPermission = true;
                                            showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                        } else {
                                            mGrantedStoragePermission = true;
                                            openGallery(false, enableCrop);
                                        }
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE)) {
                                        showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                    }
                                }
                            });
                }

                @Override
                public void onClickCancel() {

                }
            });
        } else {
            openGallery(true, enableCrop);
        }
    }

    public void checkOpenGalleryVideo(Context context) {
        if (XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(getString(R.string.permission_camera_title), getString(R.string.permission_camera_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGalleryVideo(false);
                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    mGrantedCameraPermission = true;
                                    openGalleryVideo(true);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    openGalleryVideo(false);
                                }
                            });

                }
            });
        } else if (XXPermissions.isGranted(this, Permission.CAMERA) && !XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)) {
            showPermissionIntroDialog(getString(R.string.permission_storate_title), getString(R.string.permission_storate_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGalleryVideo(true);

                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    mGrantedStoragePermission = true;
                                    openGalleryVideo(true);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                }
                            });
                }
            });
        } else if (!XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(new String[]{getString(R.string.permission_storate_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_storate_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        mGrantedStoragePermission = true;
                                        mGrantedCameraPermission = true;
                                        openGalleryVideo(true);
                                    } else {
                                        if (permissions.contains(Permission.CAMERA)) {
                                            mGrantedCameraPermission = true;
                                            showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                        } else {
                                            mGrantedStoragePermission = true;
                                            openGalleryVideo(false);
                                        }
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE)) {
                                        showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                    }
                                }
                            });
                }

                @Override
                public void onClickCancel() {

                }
            });
        } else {
            openGalleryVideo(true);
        }
    }

    private void openGallery(boolean showCamera, boolean enableCrop) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .imageEngine(GlideEngine.createGlideEngine())
                .isWeChatStyle(true)
//                        .theme(themeId)// 主题样式设置 具体参考 values/styles
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isPreviewImage(true)
                .isCamera(showCamera)// 是否显示拍照按钮
                .isEnableCrop(enableCrop)
                .isCompress(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .freeStyleCropEnabled(true)
                .showCropFrame(true)
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void openGalleryVideo(boolean showCamera) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .imageEngine(GlideEngine.createGlideEngine())/**/
                .isWeChatStyle(true)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .videoMaxSecond(30)
                .videoMinSecond(6)
                .isCamera(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

}
